package mars.mp3player.core;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Queue;

import mars.mp3player.R;
import mars.mp3player.entity.Mp3Bean;
import mars.mp3player.service.AppConstant;
import mars.mp3player.service.DownloadService;
import mars.mp3player.service.PlayerService;
import mars.mp3player.utils.LrcProcessor;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.TextView;
/**
 * mp3 
 * @author Administrator
 *
 */
public class PlayerActivity extends Activity {
	private ImageButton startButton;
	private ImageButton pauseButton;
	private ImageButton stopButton;

	private TextView lrcView;
	private ArrayList<Queue> queues;
	private UpdateLrcCallBack updateLrcCallBack;
	
	private long begin=0;
	private long currentTimeMill=0;
	private long nextTimeMill=0;
	private String message;
	private Handler handler=new Handler();
	private long pauseTimeMill=0;
	private boolean isPlaying=true;
	
	private LrcReceiver lrcReceiver;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.player);
		
		lrcView=(TextView) findViewById(R.id.lrc);
		Intent intent=getIntent();
		final Mp3Bean mp3Bean=(Mp3Bean)intent.getSerializableExtra("mp3Bean");
		
		lrcReceiver=new LrcReceiver();
		IntentFilter filter=new IntentFilter();
		filter.addAction(AppConstant.PlayerMsg.ACTION);
		this.registerReceiver(lrcReceiver, filter);
		
		startButton=(ImageButton)findViewById(R.id.startButton);
		startButton.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Intent intent=new Intent();
				intent.putExtra("mp3Bean", mp3Bean);
				intent.putExtra("MSG", AppConstant.PlayerMsg.PLAY_MSG);
				intent.setClass(PlayerActivity.this, PlayerService.class);
				prepareLrc(mp3Bean);
				PlayerActivity.this.startService(intent);
			}
		});
		
		pauseButton=(ImageButton)findViewById(R.id.pauseButton);
		pauseButton.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Intent intent=new Intent();
				intent.putExtra("MSG", AppConstant.PlayerMsg.PAUSE_MSG);
				intent.setClass(PlayerActivity.this, PlayerService.class);
				PlayerActivity.this.startService(intent);
				if(isPlaying){
					handler.removeCallbacks(updateLrcCallBack);
					pauseTimeMill=System.currentTimeMillis();
				}else{
					handler.postDelayed(updateLrcCallBack, 5);
					begin=System.currentTimeMillis()-pauseTimeMill+begin;
				}
				
				isPlaying=isPlaying ? false:true;
			}
		});
		
		stopButton=(ImageButton)findViewById(R.id.stopButton);
		stopButton.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Intent intent=new Intent();
				intent.putExtra("MSG", AppConstant.PlayerMsg.STOP_MSG);
				intent.setClass(PlayerActivity.this, PlayerService.class);
				PlayerActivity.this.startService(intent);
				handler.removeCallbacks(updateLrcCallBack);
				lrcView.setText("");
			}
		});
	}
	
	@Override
	protected void onDestroy() {
		System.out.println("onDestroy");
		super.onDestroy();
	}

	@Override
	protected void onPause() {
		System.out.println("onPause");
		super.onPause();
	}

	@Override
	protected void onRestart() {
		System.out.println("onRestart");
		super.onRestart();
	}

	@Override
	protected void onResume() {
		System.out.println("onResume");
		super.onResume();
	}
	
	@Override
	protected void onStart() {
		System.out.println("onStart");
		super.onStart();
	}

	@Override
	protected void onStop() {
		System.out.println("onStop");
		super.onStop();
	}

	public void prepareLrc(Mp3Bean mp3Bean){
		String mp3Name=mp3Bean.getMp3Name();
		String lrcName=mp3Name.substring(0,mp3Name.lastIndexOf("."))+".lrc";
		File file=new File(AppConstant.PlayerMsg.FILE_DIR+lrcName);
		if(file.exists()){
			if(file.length()==0){
				lrcView.setText("找不到歌词");
				return;
			}
			try {
				InputStream input=new FileInputStream(file);
				LrcProcessor lrcProcessor=new LrcProcessor();
				queues=lrcProcessor.process(input);
				updateLrcCallBack=new UpdateLrcCallBack(queues);
				currentTimeMill=0;
				nextTimeMill=0;
				begin=System.currentTimeMillis();
				handler.postDelayed(updateLrcCallBack,1);
			} catch (FileNotFoundException e) {
				Log.e("error",e.getMessage());
			}
			
		}else{
			Intent lrcDownload=new Intent();
			lrcDownload.putExtra("fileName", lrcName);
			lrcDownload.setClass(PlayerActivity.this, DownloadService.class);
			PlayerActivity.this.startService(lrcDownload);
		}
	}
	
	public class UpdateLrcCallBack implements Runnable {
		private Queue messages;
		private Queue timeMills;
		public UpdateLrcCallBack(ArrayList<Queue> queues){
			timeMills=queues.get(0);
			messages=queues.get(1);
		}
		
		@Override
		public void run() {
			long offset=System.currentTimeMillis()-begin;
			if(currentTimeMill==0){
				nextTimeMill=(Long)timeMills.poll();
				message=(String)messages.poll();
			}
			if(offset>=nextTimeMill){
				lrcView.setText(message);
				Object o=timeMills.poll();
				if(o!=null){
					nextTimeMill=(Long)o;
					message=(String)messages.poll();
				}else{
					handler.removeCallbacks(updateLrcCallBack);
					lrcView.setText("");
					return;
				}
			}
			currentTimeMill=currentTimeMill+10;
			handler.postDelayed(updateLrcCallBack,1);
		}
		
	}
	
	public class LrcReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			String lrcName=intent.getStringExtra("lrcName");
			if(intent.getIntExtra("failed", 0)==1){
				lrcView.setText("找不到歌词");
				return;
			}
			File file=new File(AppConstant.PlayerMsg.FILE_DIR+lrcName);
			try {
				InputStream input=new FileInputStream(file);
				LrcProcessor lrcProcessor=new LrcProcessor();
				queues=lrcProcessor.process(input);
				updateLrcCallBack=new UpdateLrcCallBack(queues);
				currentTimeMill=0;
				nextTimeMill=0;
				begin=System.currentTimeMillis();
				handler.postDelayed(updateLrcCallBack,1);
			} catch (FileNotFoundException e) {
				Log.e("error",e.getMessage());
			}
		}
		
	}
}


